<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import {
  Button,
  Card,
  Col,
  Input,
  message,
  Modal,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
} from 'ant-design-vue';

const loading = ref(false);
const attributeList = ref<any[]>([]);
const total = ref(0);

const searchForm = reactive({
  keyword: '',
  attributeType: '',
  dataType: '',
});

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

const columns = [
  {
    title: '属性名称',
    dataIndex: 'name',
    key: 'name',
    width: 150,
  },
  {
    title: '属性编码',
    dataIndex: 'code',
    key: 'code',
    width: 120,
  },
  {
    title: '属性类型',
    dataIndex: 'attributeType',
    key: 'attributeType',
    width: 120,
  },
  {
    title: '数据类型',
    dataIndex: 'dataType',
    key: 'dataType',
    width: 100,
  },
  {
    title: '是否必填',
    dataIndex: 'required',
    key: 'required',
    width: 100,
  },
  {
    title: '默认值',
    dataIndex: 'defaultValue',
    key: 'defaultValue',
    width: 120,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
  },
];

// 模拟数据
const mockAttributes = [
  {
    id: '1',
    name: '资源名称',
    code: 'resource_name',
    attributeType: 'BASIC',
    dataType: 'STRING',
    required: true,
    defaultValue: '',
    description: '资源的显示名称',
  },
  {
    id: '2',
    name: '资源编码',
    code: 'resource_code',
    attributeType: 'BASIC',
    dataType: 'STRING',
    required: true,
    defaultValue: '',
    description: '资源的唯一标识编码',
  },
  {
    id: '3',
    name: '容量',
    code: 'capacity',
    attributeType: 'BUSINESS',
    dataType: 'NUMBER',
    required: false,
    defaultValue: '1',
    description: '资源的容量或数量',
  },
  {
    id: '4',
    name: '价格',
    code: 'price',
    attributeType: 'BUSINESS',
    dataType: 'NUMBER',
    required: false,
    defaultValue: '0',
    description: '资源的价格',
  },
  {
    id: '5',
    name: '状态',
    code: 'status',
    attributeType: 'TECHNICAL',
    dataType: 'ENUM',
    required: true,
    defaultValue: 'ACTIVE',
    description: '资源的状态',
  },
];

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    await new Promise((resolve) => setTimeout(resolve, 500));

    let filteredData = mockAttributes;

    if (searchForm.keyword) {
      filteredData = filteredData.filter(
        (item) =>
          item.name.includes(searchForm.keyword) ||
          item.code.includes(searchForm.keyword),
      );
    }

    if (searchForm.attributeType) {
      filteredData = filteredData.filter(
        (item) => item.attributeType === searchForm.attributeType,
      );
    }

    if (searchForm.dataType) {
      filteredData = filteredData.filter(
        (item) => item.dataType === searchForm.dataType,
      );
    }

    const start = (pagination.current - 1) * pagination.pageSize;
    const end = start + pagination.pageSize;

    attributeList.value = filteredData.slice(start, end);
    total.value = filteredData.length;
    pagination.total = total.value;
  } catch (error) {
    console.warn('加载属性数据失败:', error);
    message.error('加载数据失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  loadData();
};

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    attributeType: '',
    dataType: '',
  });
  handleSearch();
};

// 表格变化
const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadData();
};

// 打开表单
const openAttributeForm = (type: 'create' | 'edit', record?: any) => {
  message.info(`${type === 'create' ? '新增' : '编辑'}属性功能开发中...`);
};

// 查看详情
const viewAttribute = (record: any) => {
  message.info(`查看属性"${record.name}"功能开发中...`);
};

// 删除属性
const deleteAttribute = (record: any) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除属性"${record.name}"吗？`,
    onOk: async () => {
      try {
        message.success('删除成功');
        loadData();
      } catch (error) {
        console.warn('删除失败:', error);
        message.error('删除失败');
      }
    },
  });
};

// 工具函数
const getAttributeTypeColor = (type: string) => {
  const colors: Record<string, string> = {
    BASIC: 'blue',
    BUSINESS: 'green',
    TECHNICAL: 'orange',
    CUSTOM: 'purple',
  };
  return colors[type] || 'default';
};

const getAttributeTypeText = (type: string) => {
  const texts: Record<string, string> = {
    BASIC: '基础属性',
    BUSINESS: '业务属性',
    TECHNICAL: '技术属性',
    CUSTOM: '自定义属性',
  };
  return texts[type] || type;
};

const getDataTypeColor = (type: string) => {
  const colors: Record<string, string> = {
    STRING: 'blue',
    NUMBER: 'green',
    BOOLEAN: 'orange',
    DATE: 'purple',
    ENUM: 'cyan',
  };
  return colors[type] || 'default';
};

const getDataTypeText = (type: string) => {
  const texts: Record<string, string> = {
    STRING: '字符串',
    NUMBER: '数字',
    BOOLEAN: '布尔值',
    DATE: '日期',
    ENUM: '枚举',
  };
  return texts[type] || type;
};

onMounted(() => {
  loadData();
});
</script>

<template>
  <div class="resource-attributes">
    <div class="attributes-header">
      <Row :gutter="16">
        <Col :span="8">
          <Input
            v-model:value="searchForm.keyword"
            placeholder="搜索属性名称、编码"
            allow-clear
            @change="handleSearch"
          />
        </Col>
        <Col :span="4">
          <Select
            v-model:value="searchForm.attributeType"
            placeholder="属性类型"
            allow-clear
            @change="handleSearch"
          >
            <SelectOption value="BASIC">基础属性</SelectOption>
            <SelectOption value="BUSINESS">业务属性</SelectOption>
            <SelectOption value="TECHNICAL">技术属性</SelectOption>
            <SelectOption value="CUSTOM">自定义属性</SelectOption>
          </Select>
        </Col>
        <Col :span="4">
          <Select
            v-model:value="searchForm.dataType"
            placeholder="数据类型"
            allow-clear
            @change="handleSearch"
          >
            <SelectOption value="STRING">字符串</SelectOption>
            <SelectOption value="NUMBER">数字</SelectOption>
            <SelectOption value="BOOLEAN">布尔值</SelectOption>
            <SelectOption value="DATE">日期</SelectOption>
            <SelectOption value="ENUM">枚举</SelectOption>
          </Select>
        </Col>
        <Col :span="8">
          <Space>
            <Button type="primary" @click="handleSearch">搜索</Button>
            <Button @click="handleReset">重置</Button>
            <Button type="primary" @click="openAttributeForm('create')">
              新增属性
            </Button>
          </Space>
        </Col>
      </Row>
    </div>

    <div class="attributes-content">
      <Card title="资源属性定义" :bordered="false">
        <Table
          :columns="columns"
          :data-source="attributeList"
          :loading="loading"
          :pagination="pagination"
          row-key="id"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'attributeType'">
              <Tag :color="getAttributeTypeColor(record.attributeType)">
                {{ getAttributeTypeText(record.attributeType) }}
              </Tag>
            </template>
            <template v-else-if="column.key === 'dataType'">
              <Tag :color="getDataTypeColor(record.dataType)">
                {{ getDataTypeText(record.dataType) }}
              </Tag>
            </template>
            <template v-else-if="column.key === 'required'">
              <Tag :color="record.required ? 'red' : 'green'">
                {{ record.required ? '必填' : '可选' }}
              </Tag>
            </template>
            <template v-else-if="column.key === 'action'">
              <Space>
                <Button type="link" size="small" @click="viewAttribute(record)">
                  查看
                </Button>
                <Button
                  type="link"
                  size="small"
                  @click="openAttributeForm('edit', record)"
                >
                  编辑
                </Button>
                <Button
                  type="link"
                  size="small"
                  danger
                  @click="deleteAttribute(record)"
                >
                  删除
                </Button>
              </Space>
            </template>
          </template>
        </Table>
      </Card>
    </div>
  </div>
</template>

<style scoped>
.resource-attributes {
  padding: 20px;
}

.attributes-header {
  padding: 20px;
  margin-bottom: 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.attributes-content {
  margin-bottom: 24px;
}
</style>
